package com.saicmotor.pay.base;

import android.content.Context;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;

import com.saicmotor.pay.R;
import com.saicmotor.pay.error.ErrorInfo;
import com.saicmotor.pay.view.myView.CustomProgressDialog;


public abstract class BaseActivity<VM extends BaseViewModel> extends AppCompatActivity {
    private VM viewModel;
    private View loadingView = null;
    private CustomProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewBinding();
        initOnCreate(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (progressDialog != null) {
            progressDialog.hide();
        }
    }

    public abstract void viewBinding();

    public abstract void initOnCreate(Bundle savedInstanceState);

    public abstract void initObservable();

    public void setViewModel(@NonNull VM viewModel) {
        this.viewModel = viewModel;
        viewModel.getErrorInfoMutableLiveData().observe(this, new Observer<ErrorInfo>() {
            @Override
            public void onChanged(ErrorInfo errorInfo) {
                onError(errorInfo);
            }
        });
        initObservable();
    }

    public abstract void onError(ErrorInfo errorInfo);

    public VM getViewModel() {
        if (viewModel == null) {
            throw new NullPointerException("You should setViewModel first!");
        }
        return viewModel;
    }

    public void showLoading(Context context) {
        //实例化自定义CustomProgressDialog
        progressDialog = new CustomProgressDialog(context, R.style.progressDialog);
        //设置不可点击外边取消动画
        progressDialog.setCanceledOnTouchOutside(false);
        //动画显示
        progressDialog.show();
    }

    public void hideLoading() {
        if (progressDialog != null) {
            progressDialog.hide();
        }
    }
}
